﻿/*===================================================
* CLR版本  : 4.0.30319.42000 
* 类名称   : ObjectPoor
* 文 件 名 : ObjectPoor 
* 类描述   :
* 创建人   : oream
* 创建时间 : 2018/3/7 21:50:35
* 修改人   : 
* 修改时间 :
* 版本： @version 1.0
=====================================================*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model;
using System.Threading.Tasks;

namespace Hotfix
{
  public class ObjectPool
  {
    private Dictionary<Type, Queue<Disposer>> dicObjectPool = new Dictionary<Type, Queue<Disposer>>();

    private Disposer FetchObject(Type type)
    {
      Queue<Disposer> tmpQueuePool;
      if (!this.dicObjectPool.TryGetValue(type, out tmpQueuePool))
      {
        tmpQueuePool = new Queue<Disposer>();
        this.dicObjectPool.Add(type, tmpQueuePool);
      }
      Disposer tmpDisposer;
      if (tmpQueuePool.Count > 0)
      {
        tmpDisposer = tmpQueuePool.Dequeue();
        tmpDisposer.Id = IDGenerater.GenerateId();
        return tmpDisposer;
      }
      tmpDisposer = Activator.CreateInstance(type) as Disposer;
      return tmpDisposer;
    }

    /// <summary>
    /// 获取对象池的对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public T FetchObject<T>() where T : Disposer
    {
      Disposer disposer = FetchObject(typeof(T));
      disposer.IsFromPool = true;
      return disposer as T;
    }

    /// <summary>
    /// 放入对象池
    /// </summary>
    /// <param name="disposer"></param>
    public void Recycle(Disposer disposer)
    {
      Queue<Disposer> tmpQueuePool;
      if (!this.dicObjectPool.TryGetValue(disposer.GetType(), out tmpQueuePool))
      {
        tmpQueuePool = new Queue<Disposer>();
        this.dicObjectPool.Add(disposer.GetType(), tmpQueuePool);
      }
      tmpQueuePool.Enqueue(disposer);
    }
  }
}
